package com.rightsidetech.http.controller.userApp.paycallback;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.gexin.fastjson.JSONArray;
import com.rightsidetech.activity.dto.response.store.app.MtActivityOrderResp;
import com.rightsidetech.activity.entity.*;
import com.rightsidetech.activity.service.ActCouponUserService;
import com.rightsidetech.activity.service.ActGiftService;
import com.rightsidetech.activity.service.MtActivityAppService;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.EnumPayMode;
import com.rightsidetech.commom.enums.StoreActivityEnum;
import com.rightsidetech.commom.push.EnumMsgType;
import com.rightsidetech.commom.utils.IKExpressionUtil;
import com.rightsidetech.commom.utils.StringUtil;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.config.WechatConfig;
import com.rightsidetech.http.task.MassageTask;
import com.rightsidetech.http.wechatutil.WechatUtil;
import com.rightsidetech.mall.dto.response.CommodityOrderDetailResp;
import com.rightsidetech.mall.entity.MallCommoditySpecs;
import com.rightsidetech.mall.entity.MallGiftCommodity;
import com.rightsidetech.mall.service.MallCommodityService;
import com.rightsidetech.mall.service.MallGiftCommodityService;
import com.rightsidetech.system.dtos.request.store.StoreCommodityIntegralDetialReq;
import com.rightsidetech.system.dtos.request.store.StoreCommodityIntegralReq;
import com.rightsidetech.system.dtos.response.store.SysStoreOrderDetailResp;
import com.rightsidetech.system.entity.SysLevelRule;
import com.rightsidetech.system.entity.store.SysStoreAccountInfo;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.service.*;
import com.rightsidetech.trade.entity.TdCommodityOrderDetails;
import com.rightsidetech.trade.entity.TdCommodityUserOrder;
import com.rightsidetech.trade.entity.TdCouponUseRecord;
import com.rightsidetech.trade.service.TdCommodityUserOrderService;
import com.rightsidetech.trade.service.TdCouponUseService;
import com.rightsidetech.user.dtos.response.LoginInfoResp;
import com.rightsidetech.user.entity.UsUserAccountInfo;
import com.rightsidetech.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/callback")
@ShenyuSpringMvcClient(path = "/callback/**")
@Api(tags = "用户订单相关")
@Slf4j
public class PayCallBackController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private WechatConfig wechatConfig;
    @Resource
    private TdCommodityUserOrderService tdCommodityUserOrderService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private LevelRuleService levelRuleService;
    @Resource
    private TdCouponUseService tdCouponUseService;
    @Autowired
    private MassageTask massageTask;
    @Resource
    private SysStoreStorkService sysStoreStorkService;
    @Resource
    private MallCommodityService mallCommodityService;
    @Resource
    private ActGiftService actGiftService;
    @Resource
    private MallGiftCommodityService mallGiftCommodityService;
    @Resource
    private MtActivityAppService mtActivityAppService;


    @Resource
    private SysRuleCommodityIntegralService sysRuleCommodityIntegralService;
    @Resource
    private SysStoreIntegralService sysStoreIntegralService;
    @Resource
    private ActCouponUserService actCouponUserService;

    @Log
    @ApiOperation("微信支付回调")
    @PostMapping("/wechat")
    @ApiIgnore
    public void doPost() {

        try {
            log.info("微信进行回调接口");
            InputStream inputStream = request.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();
            String result = outputStream.toString("utf-8");// 获取微信调用我们notify_url的返回信息

            boolean flag = WechatUtil.checkIsSignValidFromResponseString(result, wechatConfig.getApiKey());
            if (!flag) {
                //System.out.println("微信支付sign验证不通过");
                log.error("微信回调sign验证不通过");
                response.getWriter().print("<xml><return_code><![CDATA[FAIL]]></return_code></xml>");
                return;
            }
            response.getWriter().print("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
            log.info("微信回调成功，并且已经响应微信");
            wechatUserPayCallBackk(result);
        } catch (Exception e) {
            log.error("回调微信支付失败", e);
        }
    }


    /**
     * 获取请求参数中所有的信息
     *
     * @param request
     * @return
     */
    public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //在报文上送时，如果字段的值为空，则不上送<下面的处理为在获取所有参数数据时，判断若值为空，则删除这个字段>
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }


    @Log
    @ApiOperation("测试成功支付接口")
    @GetMapping("/test")
    public ResponseData testPay(@ApiParam(required = true, name = "orderNo",
            value = "订单编号") @RequestParam("orderNo") String orderNo) {
        if (StringUtils.isEmpty(orderNo)) {
            return ResponseData.fail("订单编号不能为空");
        }
        TdCommodityUserOrder tdCommodityUserOrder = tdCommodityUserOrderService.findByOrderNo(orderNo);

        if (StringUtil.isNullorEmpty(tdCommodityUserOrder)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }
        if (tdCommodityUserOrder.getOrderStatus() != 0) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }

        //判断门店
        SysStoreOrderDetailResp sysStoreOrderDetailResp = sysStoreInfoService.findOrderDetailByStoreId(tdCommodityUserOrder.getStoreId());
        if (StringUtil.isNullorEmpty(sysStoreOrderDetailResp)) {
            return ResponseData.fail(CodeIdEnum.NonStoreInfo);
        }
        if (sysStoreOrderDetailResp.getStatus() == -1){
            return ResponseData.fail(CodeIdEnum.STOREClOSEDINFO);
        }
        //判断优惠券
        //根据订单号查询优惠券记录, 判断该订单是否使用了优惠券
        TdCouponUseRecord tdCouponUseRecord = tdCouponUseService.selectByOrderNo(orderNo);
        if(!StringUtils.isEmpty(tdCouponUseRecord)){
            //查询领取记录
            ActCouponGetRecord actCouponGetRecord = actCouponUserService.selectGetRecordByCodeAndStatusAndDate(tdCouponUseRecord.getCode());
            //判断优惠券状态
            if(StringUtils.isEmpty(actCouponGetRecord)){
                return ResponseData.fail("订单优惠券不存在");
            }
            //校验优惠券
            ResponseData couponResp = checkCode(actCouponGetRecord,tdCommodityUserOrder.getUserInfoId(),tdCommodityUserOrder.getAgentId(), tdCommodityUserOrder.getStoreId(),tdCommodityUserOrder.getTotalAmount());
            if(couponResp.getCodeId() != 1){
                return couponResp;
            }
        }

        //判断商品
        List<TdCommodityOrderDetails> commodityList = tdCommodityUserOrderService.findCommodityByOrderNo(tdCommodityUserOrder.getOrderNo(), (byte) 0);
        for (TdCommodityOrderDetails com1 : commodityList) {
            CommodityOrderDetailResp mallDetail = mallCommodityService.findOrderDetailByCommodityId(com1.getCommodityId());
            if (StringUtil.isNullorEmpty(mallDetail)) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
            }
            if (mallDetail.getCommodityStatus() != 3) {
                return ResponseData.fail(CodeIdEnum.NOCOMMODITYSTATUS);
            }
            boolean b6 = mallCommodityService.checkCommodityByAgentId(sysStoreOrderDetailResp.getAgentId(), com1.getCommodityId());
            if (!b6) {
                return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITY);
            }

            //判断换购商品
            List<TdCommodityOrderDetails> hgList = tdCommodityUserOrderService.findTdOrderDetailByParentId(com1.getId(), (byte) 2);
            for (TdCommodityOrderDetails com2 : hgList) {
                //判断赠品的状态
                MallGiftCommodity mallGiftCommodity = mallGiftCommodityService.selectTypeIdByGiftId(com2.getCommodityId());

                if (StringUtil.isNullorEmpty(mallGiftCommodity)) {
                    return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
                }

                boolean b4 = actGiftService.checkGift(mallDetail.getTypeId(), com2.getCommodityId(), tdCommodityUserOrder.getStoreId());
                if (!b4) {
                    return ResponseData.fail(CodeIdEnum.NOFINDCOMMODITYGIFT);
                }
            }
        }

        return payOrderFinish(orderNo, "001", (byte) 1);
    }

    // 校验优惠券信息
    private ResponseData checkCode(ActCouponGetRecord actCouponGetRecord,Long userInfoId,Long agentId, Long storeId,BigDecimal totalAmount){

        if(StringUtils.isEmpty(actCouponGetRecord)){
            return ResponseData.fail("优惠券不存在");
        }
        //判断是用户优惠券还是门店优惠券
        if(actCouponGetRecord.getTarget() == 0){
            //判断是否是该用户的优惠券
            if(!actCouponGetRecord.getUserStoreId().equals(userInfoId)){
                return ResponseData.fail("优惠券不存在");
            }
        }else{
            //判断门店是否还能使用优惠券, 根据门店使用次数
            int storeCount = actCouponUserService.countUsedCouponByStoreId(actCouponGetRecord.getActivityId(),storeId);
            if(storeCount >= actCouponGetRecord.getGetQuantity()){
                return ResponseData.fail("优惠券已使用完");
            }
        }
        //判断使用范围是否满足条件
        List<Long> list = JSONArray.parseArray(actCouponGetRecord.getUseScope(),Long.class);
        boolean flag = list.contains(agentId);
        if(!flag){
            return ResponseData.fail("该门店不能使用该优惠券");
        }

        //判断金额是否满足条件
        if(totalAmount.longValue() <= actCouponGetRecord.getMinConsumeAmount() ){
            return ResponseData.fail("不满足最低消费金额");
        }

        return ResponseData.success();
    }


    //订单支付完成, 支付方式, 1-微信, 2-测试,
    public ResponseData payOrderFinish(String orderNo, String otherOrderNo, byte tradeChannel) {
        //查询订单信息
        TdCommodityUserOrder td1 = tdCommodityUserOrderService.findByOrderNo(orderNo);
        if (StringUtil.isNullorEmpty(td1)) {
            return ResponseData.fail(CodeIdEnum.NonOrder);
        }

        if (td1.getOrderStatus() != 0) {
            return ResponseData.fail(CodeIdEnum.ErrorOrderStatus);
        }

        //1.修改该订单信息
        ResponseData resp = tdCommodityUserOrderService.updateOrder(orderNo, otherOrderNo, tradeChannel);
        if (resp.getCodeId() != 1) {
            return resp;
        }

        //使用优惠券
        TdCouponUseRecord record = tdCouponUseService.selectByOrderNo(orderNo);
        if (!ObjectUtils.isEmpty(record)) {
            //判断优惠券状态是否为待付款
            if(record.getStatus() == 0){
                //可以使用优惠券, 调整订单优惠券信息
                tdCouponUseService.updateByIdAndCode(record.getId(),record.getCode());

                //修改code表,
                actCouponUserService.updateActCouponActivityCode(record.getCode(),(byte) 2);
                //修改getRecord表
                //判断是用户优惠券还是门店优惠券
                ActCouponGetRecord actCouponGetRecord = actCouponUserService.selectGetRecordByCode(record.getCode());
                if(!StringUtils.isEmpty(actCouponGetRecord)){
                    ActCouponGetRecord getRecord = new ActCouponGetRecord();
                    getRecord.setId(actCouponGetRecord.getId());
                    getRecord.setStatus((byte) 1);
                    getRecord.setUpdatedAt(new Date());

                    //判断是否是用户还是门店优惠券
                    if(actCouponGetRecord.getTarget() == 1){
                        //门店
                        getRecord.setUserStoreId(td1.getStoreId());
//                        getRecord.setUsUserName(td1.getUsName());
//                        getRecord.setPhoneNo(td1.getUsPhoneNo());
                    }
                    actCouponUserService.updateGetRecord(getRecord);
                    //添加userdRecord表
                    LoginInfoResp loginInfoResp = userInfoService.getUserInfoByUserInfoId(td1.getUserInfoId());
                    ActCouponUsedRecord actCouponUsedRecord = new ActCouponUsedRecord();
                    actCouponUsedRecord.setActivityId(actCouponGetRecord.getActivityId());
                    actCouponUsedRecord.setCode(actCouponGetRecord.getCode());
                    actCouponUsedRecord.setStoreId(td1.getStoreId());
                    actCouponUsedRecord.setUserInfoId(td1.getUserInfoId());
                    if(!StringUtils.isEmpty(loginInfoResp)){
                        actCouponUsedRecord.setUsUserName(loginInfoResp.getPetName());
                        actCouponUsedRecord.setPhoneNo(loginInfoResp.getPhoneNo());
                    }
                    actCouponUsedRecord.setCreatedAt(new Date());
                    actCouponUsedRecord.setIsDeleted((byte) 0);
                    actCouponUserService.insertUsedRecord(actCouponUsedRecord);

                    if(actCouponGetRecord.getTarget() == 1){
                        //进行推送
                        massageTask.storePushOrder(td1.getStoreId(), EnumMsgType.Coupon_used.getName(), EnumMsgType.Coupon_used.getValue(), actCouponGetRecord.getActivityId().toString());
                    }
                }

/*                ActUpdateStatisReq req = new ActUpdateStatisReq();
                req.setActivityId(record.getActivityId());
                req.setDiscountAmount(record.getDiscountAmount());
                req.setPayableAmount(record.getTotalAmount());
                req.setPayAmount(record.getActualAmount());
                actCouponUserService.updateStatis(req);*/
            }


        }

        //添加出库记录, 判断是否到店自取 修改库存
        if (td1.getOrderType() == 1) {
            updateStoreInfo(td1.getOrderNo(), td1.getStoreId());
        }


        //2.修改用户订单数,用户
        TdCommodityUserOrder tdCommodityUserOrder = (TdCommodityUserOrder) resp.getResData();
        ResponseData resp1 = userInfoService.updateUsUserStatis(tdCommodityUserOrder.getUserInfoId(), tdCommodityUserOrder.getActualAmount());
        if (resp1.getCodeId() != 1) {
            return resp1;
        }
        //3.门店
        ResponseData resp2 = sysStoreInfoService.updateStoreOrder(tdCommodityUserOrder.getStoreId(), tdCommodityUserOrder.getActualAmount());
        if (resp2.getCodeId() != 1) {
            return resp2;
        }
        //4.修改用户等级
        SysLevelRule ruleByOrderNum = levelRuleService.findLevelRuleByOrderNum(1L);
        if (!ObjectUtils.isEmpty(ruleByOrderNum)) {
            UsUserAccountInfo accountInfo = new UsUserAccountInfo();
            accountInfo.setUserInfoId(tdCommodityUserOrder.getUserInfoId());
            accountInfo.setLevel(Long.parseLong(ruleByOrderNum.getLevel().toString()));
            accountInfo.setLevelName(ruleByOrderNum.getLevelName());
            accountInfo.setUpdatedAt(new Date());
            userInfoService.updateUserLevel(accountInfo);
        }
        //门店计算积分
        SysStoreAccountInfo accountInfo = sysStoreInfoService.selectByStoreId(tdCommodityUserOrder.getStoreId());
        List<TdCommodityOrderDetails> commodityList = tdCommodityUserOrderService.findCommodityByOrderNo(orderNo, (byte) 0);
        if (CollUtil.isNotEmpty(commodityList)) {
            List<StoreCommodityIntegralDetialReq> comIntReqList = new ArrayList<>();
            BigDecimal decimal = new BigDecimal("0");
            for (TdCommodityOrderDetails orderDetails : commodityList) {
                BigDecimal ruleValue = sysRuleCommodityIntegralService.findRuleValueByIdAndBarCode(orderDetails.getCommodityId(), orderDetails.getCommodityBarCode());
                if (ObjectUtil.isNotEmpty(ruleValue)) {
                    if (ObjectUtil.isNotEmpty(accountInfo)) {
                        for (Integer i = 0; i < orderDetails.getCommodityNum(); i++) {
                            StoreCommodityIntegralDetialReq scidq = new StoreCommodityIntegralDetialReq();
                            scidq.setCommodityName(orderDetails.getCommodityName());
                            scidq.setCommodityId(orderDetails.getCommodityId());
                            scidq.setBarCode(orderDetails.getCommodityBarCode());
                            scidq.setSpecs(orderDetails.getCommoditySpecs());
                            scidq.setIntegral(ruleValue);
                            decimal = decimal.add(ruleValue);
                            comIntReqList.add(scidq);
                        }
                    }
                }
            }
            if (CollUtil.isNotEmpty(comIntReqList)) {
                StoreCommodityIntegralReq intReq = new StoreCommodityIntegralReq();
                intReq.setStoreId(tdCommodityUserOrder.getStoreId());
                intReq.setAccountId(accountInfo.getId());
                intReq.setOrderNo(orderNo);
                intReq.setList(comIntReqList);
                SysStoreAccountInfo acc = new SysStoreAccountInfo();
                acc.setId(accountInfo.getId());
                acc.setPoint(accountInfo.getPoint().add(decimal));
                sysStoreInfoService.updateAccountInfo(acc);
                intReq.setIntegral(decimal);
                sysStoreIntegralService.insertCommodityIntegral(intReq, (byte) 0);
            }
        }
        SysStoreInfo storeInfo = sysStoreInfoService.selectByPrimaryKey(tdCommodityUserOrder.getStoreId());
        if (ObjectUtil.isEmpty(storeInfo)) {
            return ResponseData.fail("未找到门店");
        }
        //判断门店活动
        List<MtActivityOrderResp> actList = mtActivityAppService.orderAndActivity(tdCommodityUserOrder.getStoreId());
        if (CollUtil.isNotEmpty(actList)) {
            for (MtActivityOrderResp orderResp : actList) {
                //判断再活动时间内
                Date date = new Date();
                if (date.after(orderResp.getStartTime()) && date.before(orderResp.getEndTime())) {
                    MtUserJoinActivityProcess process = new MtUserJoinActivityProcess();
                    process.setActId(orderResp.getId());
                    process.setActName(orderResp.getName());
                    process.setActStart(orderResp.getStartTime());
                    process.setActEnd(orderResp.getEndTime());
                    process.setUserAccountId(tdCommodityUserOrder.getStoreId());
                    process.setUserLoginName(storeInfo.getStoreBoss());
                    process.setUserPhone(storeInfo.getConnectWay());
                    process.setDicCode(orderResp.getField());
                    process.setCreatedAt(new Date());
                    process.setUserArea(storeInfo.getAreaId());
                    process.setUserImage(storeInfo.getStoreImage());
                    if (StoreActivityEnum.HJ001.getDicCode().equals(orderResp.getField())) {
                        process.setBizId(td1.getId());
                        mtActivityAppService.insertProcess(process);

                    } else if (StoreActivityEnum.HJ004.getDicCode().equals(orderResp.getField())) {
                        if (CollUtil.isNotEmpty(commodityList)) {
                            boolean flag = isLottery(orderResp.getId());
                            f1:
                            for (TdCommodityOrderDetails orderDetails : commodityList) {
                                if (flag) {
                                    MtActivityRuleBusiness business = mtActivityAppService.selectBusinessByActIdAndComId(orderResp.getId(), String.valueOf(orderDetails.getCommodityId()));
                                    if (ObjectUtil.isEmpty(business)) {
                                        continue f1;
                                    }
                                }
                                for (Integer i = 0; i < orderDetails.getCommodityNum(); i++) {
                                    process.setBizId(orderDetails.getCommodityId());
                                    mtActivityAppService.insertProcess(process);
                                }
                            }
                        }
                    }
                }
            }
            for (MtActivityOrderResp orderResp : actList) {
//                if(isDivide(orderResp.getId())){
                //排名活动不修改达标状态
                MtActivityRule mtActivityRule = mtActivityAppService.selectRuleByMoldAndActId(orderResp.getId(), StoreActivityEnum.PB000.getDicType());
                if (!ObjectUtils.isEmpty(mtActivityRule)) {
                    continue;
                }
                int count = mtActivityAppService.processCount(orderResp.getId(), storeInfo.getId());
                Map<String, Object> map = new HashMap<>();
                map.put("count", count);
                boolean flag = IKExpressionUtil.executeIs("count" + orderResp.getExpression(), map);
                if (flag) {
                    mtActivityAppService.updateUserJoin(orderResp.getId(), storeInfo.getId(), (short) 1);
                }
//                }
            }
        }

        //上门服务订单
        if (td1.getOrderType() == 0) {
            //5.发送门店推送消息
            massageTask.storePushOrder(td1.getStoreId(), EnumMsgType.TODOOR_SERVICE.getName(), EnumMsgType.TODOOR_SERVICE.getValue(), orderNo);
        }

        return ResponseData.success();
    }

    private boolean isDivide(Long actId) {
        MtActivityRule rule = mtActivityAppService.selectRuleByMoldAndActId(actId, StoreActivityEnum.PB000.getDicType());
        if (ObjectUtil.isNotEmpty(rule)) {
            return false;
        }
        MtActivityRule rule1 = mtActivityAppService.selectRuleByFieldAndActId(actId, StoreActivityEnum.CJ002.getDicCode());
        return ObjectUtil.isNotEmpty(rule1);
    }

    private void updateStoreInfo(String orderNo, Long storeId) {
        List<TdCommodityOrderDetails> tdDetail = tdCommodityUserOrderService.findCommodityByOrderNo(orderNo, (byte) 0);
        if (null != tdDetail && tdDetail.size() > 0) {
            for (TdCommodityOrderDetails td2 : tdDetail) {
                if (!StringUtils.isEmpty(td2.getCommodityBarCode())) {
                    MallCommoditySpecs mallCommoditySpecs = mallCommodityService.selectSpecsByCommodityAndBarCode(td2.getCommodityId(), td2.getCommodityBarCode());
                    if (null != mallCommoditySpecs) {
                        sysStoreStorkService.outStork(storeId, mallCommoditySpecs.getId(), td2.getCommodityId(), td2.getCommodityNum().longValue());
                    } else {
                        sysStoreStorkService.outStork(storeId, null, td2.getCommodityId(), td2.getCommodityNum().longValue());
                    }
                } else {
                    sysStoreStorkService.outStork(storeId, null, td2.getCommodityId(), td2.getCommodityNum().longValue());
                }
            }
        }
    }

    public void wechatUserPayCallBackk(String result) throws Exception {
        Document doc = DocumentHelper.parseText(result);
        Map<String, String> params = (Map<String, String>) xml2map(doc.getRootElement());
        String return_code = params.get("return_code");
        String result_code = params.get("result_code");
        String orderNo = params.get("out_trade_no");
        String otherOrderNo = params.get("transaction_id");
        String attach = params.get("attach");
        //微信回调支付成功后
        if ("SUCCESS".equals(result_code) && "SUCCESS".equals(return_code)) {
            Map<String, String> additionParamMap = getStringToMap(attach);
            String payMode = additionParamMap.get("payMode");
            String payWay = additionParamMap.get("payWay");
            boolean flag = false;
            if (StrUtil.equals(EnumPayMode.PAY_CHARGE.getValue(), payMode)) {
                //充值回调(暂时没有)

            } else if (StrUtil.equals(EnumPayMode.PAY_COMSUME.getValue(), payMode)) {
                payOrderFinish(orderNo, otherOrderNo, (byte) 1);
            }
            if (flag) {
                log.info("SUCCESS重要信息--------------------订单号:" + orderNo + "交易完成------------------------------SUCCESS");
            }
        } else {
            log.info("FAIL---------------订单号:" + orderNo + "微信回调显示支付失败------------------------------FAIL");
        }
    }

    /**
     * 将xml解析成map格式
     *
     * @param element 参数
     * @return map
     */
    private static Object xml2map(Element element) {
        Map<String, Object> map = new HashMap<>();
        List<Element> elements = element.elements();
        if (elements.size() == 0) {
            map.put(element.getName(), element.getText());
            if (!element.isRootElement()) {
                return element.getText();
            }
        } else if (elements.size() == 1) {
            map.put(elements.get(0).getName(), xml2map(elements.get(0)));
        } else if (elements.size() > 1) {
            // 多个子节点的话就得考虑list的情况了，比如多个子节点有节点名称相同的
            // 构造一个map用来去重
            Map<String, Element> tempMap = new HashMap<>();
            for (Element ele : elements) {
                tempMap.put(ele.getName(), ele);
            }
            Set<String> keySet = tempMap.keySet();
            for (String string : keySet) {
                List<Element> elements2 = element.elements(new QName(string));
                // 如果同名的数目大于1则表示要构建list
                if (elements2.size() > 1) {
                    List<Object> list = new ArrayList<>();
                    for (Element ele : elements2) {
                        list.add(xml2map(ele));
                    }
                    map.put(string, list);
                } else {
                    // 同名的数量不大于1则直接递归去
                    map.put(string, xml2map(elements2.get(0)));
                }
            }
        }

        return map;
    }

    /**
     * String转map
     *
     * @param str
     * @return
     */
    public static Map<String, String> getStringToMap(String str) {
        //根据逗号截取字符串数组
        String[] str1 = str.split(",");
        //创建Map对象
        Map<String, String> map = new HashMap<>();
        //循环加入map集合
        for (int i = 0; i < str1.length; i++) {
            //根据":"截取字符串数组
            String[] str2 = str1[i].split("-");
            //str2[0]为KEY,str2[1]为值
            map.put(str2[0], str2[1]);
        }
        return map;
    }

    private boolean isLottery(Long actId) {
        return ObjectUtil.isNotEmpty(mtActivityAppService.selectRuleByFieldAndActId(actId, StoreActivityEnum.CJ002.getDicCode()));
    }

}
